//
// Created by martin on 2/6/22.
//

#include "LogFile.h"
#include "muduo/base/FileUtil.h"
#include "muduo/base/ProcessInfo.h"

using namespace muduo;

LogFile::LogFile(const std::string &basename,
                 off_t rollSize,
                 bool threadSafe,
                 int flushInterval,
                 int checkEveryN)
        : basename_(basename),
        rollSize_(rollSize),
        flushInterval_(flushInterval),
        checkEveryN_(checkEveryN),
        count_(0),
        mutex_(threadSafe ? new MutexLock : NULL),
        startOfPeriod_(0),
        lastRoll_(0),
        lastFlush_(0)
{
    assert(basename.find('/') == string::npos);
    rollFile();
}

LogFile::~LogFile() = default;

void LogFile::append(const char *logline, int len)
{
    if (mutex_)
    {
        MutexLockGuard lock(*mutex_);
        append_unlocked(logline, len);
    }
    else
    {
        append_unlocked(logline, len);
    }
}

void LogFile::append_unlocked(const char *logline, int len)
{
    file_->append(logline, len);

    if (file_->writtenBytes() > rollSize_)
    { // written bytes to file_ > roll threshold (rollSize_)
        rollFile();
    }
    else
    {
        ++count_;
        if (count_ >= checkEveryN_)
        {
            count_ = 0;
            time_t now = ::time(NULL);
            time_t thisPeriod_ = now / kRollPerSeconds_ * kRollPerSeconds_;

            if (thisPeriod_ != startOfPeriod_)
            { // new period, roll file for log
                rollFile();
            }
            else if (now - lastFlush_ > flushInterval_)
            { // timeout ( flushInterval_ = 3 seconds)
                lastFlush_ = now;
                file_->flush();
            }
        }
    }
}

/**
 * roll file to next window
 * @details there are
 * @return
 */
bool LogFile::rollFile()
{
    time_t now = 0;
    string filename = getLogFileName(basename_, &now);
    time_t start = now / kRollPerSeconds_ * kRollPerSeconds_;

    if (now > lastRoll_)
    { // to avoid identical roll by roll time
        lastRoll_ = now;
        lastFlush_ = now;
        startOfPeriod_ = start;
        // create new log file with new filename
        file_.reset(new FileUtil::AppendFile(filename));
        return true;
    }
    return false;
}

/**
 * get a new log file name based on basename and now time
 * @details log file name format:
 * basename + now + hostname + pid + ".log"
 * basename is defined by user_, now means seconds since the Epoch,
 * hostname is current host name(not username), pid is current proc id.
 * @param basename [in] to make up a full file name for a new log file
 * @param now [out] second since the Epoch (UTC)
 * @return new log file name
 * @note why now is out param? two reason: 1) the caller can get the same time;
 * 2) to save one time syscall
 */
string LogFile::getLogFileName(const string &basename, time_t *now)
{
    string filename;
    filename.reserve(basename.size() + 64); // extra 64 bytes for timestamp etc.
    filename = basename;

    char timebuf[32];
    struct tm tmbuf;
    *now = time(NULL);
    gmtime_r(now, &tmbuf); // FIXME: localtime_r ?
    strftime(timebuf, sizeof(timebuf), ".%Y%m%d-%H%M%S.", &tmbuf);
    filename += timebuf;

    filename += ProcessInfo::hostname();

    char pidbuf[32];
    snprintf(pidbuf, sizeof(pidbuf), ".%d", ProcessInfo::pid());
    filename += pidbuf;
    filename += ".log";

    return filename;
}

void LogFile::flush()
{
    if (mutex_)
    {
        MutexLockGuard lock(*mutex_);
        file_->flush();
    }
    else
    {
        file_->flush();
    }
}
